package com.jiyun.myFile;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author 朱庆辉
 * @Date 2023/7/28 16:05
 * @Email 1018276870@qq.com
 */
@Component
public class MyFile implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("token");
        String path = request.getURI().getPath();
        if (path.contains("/login")){
            return chain.filter(exchange);
        }
        if (StringUtils.isNotBlank(token)){
            boolean verify = JWTUtil.verify(token, "token".getBytes());
            if (verify){
                return chain.filter(exchange);
            }
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
